package com.tbit.main.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.tbit.main.dao.core.AccountDao;
import com.tbit.main.dao.core.RideLogDao;
import com.tbit.main.dao.core.RoleMenuDao;
import com.tbit.main.dao.core.WorkbenchDao;
import com.tbit.main.dao.log.MoveLogDao;
import com.tbit.main.pojo.AccountConfig;
import com.tbit.main.pojo.Menu;
import com.tbit.main.pojo.QuickAccess;
import com.tbit.main.pojo.Result;
import com.tbit.main.pojo.VO.GetDataVO;
import com.tbit.main.pojo.VO.QuickAccessVO;
import com.tbit.main.pojo.VO.WorkOrderVO;
import com.tbit.main.pojo.dto.AddQuickAccessDTO;
import com.tbit.main.pojo.dto.QueryQuickAccessDTO;
import com.tbit.main.pojo.dto.TodoItemsDTO;
import com.tbit.main.service.AccountConfigService;
import com.tbit.main.service.WorkbenchService;
import com.tbit.manager.api.AccountDayStatApi;
import com.tbit.manager.api.WorkbenchApi;
import com.tbit.manager.api.dto.ItemsDTO;
import com.tbit.manager.api.dto.OperationalDataDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 工作台
 *
 * @author <a href="mailto:liu.haoxiang@tbit.com.cn">BUGXiang</a>
 * @version 1.0
 * @since 2024-11-26
 */
@Service
@Slf4j
public class WorkbenchServiceImpl implements WorkbenchService {

    @Resource
    private WorkbenchDao workbenchDao;
    @Resource
    private RoleMenuDao roleMenuDao;
    @Resource
    private RideLogDao rideLogDao;
    @Resource
    private MoveLogDao moveLogDao;
    @Resource
    private AccountDao accountDao;
    @Autowired
    private WorkbenchApi workbenchApi;
    @Autowired
    private AccountDayStatApi accountDayStatApi;
    @Resource
    private AccountConfigService accountConfigService;



    /**
     * 查询常用功能
     *
     * @param dto dto
     * @return result
     */
    @Override
    public Result<QuickAccessVO> queryQuickAccess(QueryQuickAccessDTO dto) {
        if (Objects.isNull(dto.getBrandId()) || Objects.isNull(dto.getAccountUserId())) {
            return Result.error("参数错误");
        }
        //获取运维端所有菜单信息
        Map<Integer, Menu> menuMap = roleMenuDao.selectMainMenu().stream().collect(Collectors.toMap(Menu::getMenuId, Menu -> Menu));
        if (CollectionUtil.isEmpty(menuMap)) {
            return Result.error("菜单信息为空");
        }
        QuickAccessVO quickAccessVO = new QuickAccessVO();
        List<QuickAccess> quickAccesses = workbenchDao.queryQuickAccess(dto).stream().sorted(Comparator.comparing(QuickAccess::getSort)).collect(Collectors.toList());
        List<Menu> menuList = quickAccesses.stream()
                .map(quickAccess -> menuMap.get(quickAccess.getMenuId()))
                .filter(Objects::nonNull).collect(Collectors.toList());
        quickAccessVO.setIsUsed(workbenchDao.selectIsUsed(dto) > 0);
        quickAccessVO.setMenuData(menuList);
        return Result.success(quickAccessVO);
    }


    /**
     * 添加常用功能
     * @param dto dto
     * @return result
     */
    @Override
    public Result<Object> addQuickAccess(AddQuickAccessDTO dto) {
        workbenchDao.deleteQuickAccess(dto);
        if (StrUtil.isNotEmpty(dto.getMenuData())){
            Map<String, Menu> permsMap = roleMenuDao.selectMainMenu().stream().collect(Collectors.toMap(Menu::getPerms, Menu -> Menu));
            String[] split = dto.getMenuData().split(",");
            List<QuickAccess> quickAccesses = new ArrayList<>();
            int sort = 1;
            for (String s : split) {
                QuickAccess quickAccess = new QuickAccess();
                quickAccess.setSort(sort);
                quickAccess.setType(0);
                quickAccess.setAddTime(new Date());
                quickAccess.setBrandId(dto.getBrandId());
                quickAccess.setAccountUserId(dto.getAccountUserId());
                quickAccess.setMenuId(permsMap.getOrDefault(s, new Menu()).getMenuId());
                quickAccesses.add(quickAccess);
                sort++;
            }
            workbenchDao.batchInsertQuickAccess(quickAccesses);
        }
        return Result.success();
    }

    /**
     * 获取数据
     * @param dto dto
     */
    @Override
    public GetDataVO getData(TodoItemsDTO dto) {
        //获取订单信息
        GetDataVO vo = rideLogDao.getTodayCount(dto);
        Date date = new Date();
        Map<String, Object> operationMap = accountDayStatApi.operationalData(new OperationalDataDTO(date, date, accountDao.getByAccount(dto.getAccountId()), dto.getAccountId().toString()));
        if (CollectionUtil.isNotEmpty(operationMap)){
            double operatingIncomeSum = Double.parseDouble(operationMap.getOrDefault("operating_income_sum", 0).toString());
            double operatingExpensesSum = Double.parseDouble(operationMap.getOrDefault("operating_expenses_sum", 0).toString());
            double money = NumberUtil.sub(operatingIncomeSum, operatingExpensesSum);
            AccountConfig accountConfig = accountConfigService.getByAccountId(dto.getAccountId());
            if (Objects.nonNull(accountConfig) && Objects.nonNull(accountConfig.getPayRate())){
                money = NumberUtil.sub(operatingIncomeSum, operatingExpensesSum, NumberUtil.mul(NumberUtil.div(accountConfig.getPayRate().intValue(), 1000), operatingIncomeSum)).doubleValue();
            }
            log.info("运营收入：{}， 运营支出：{}，净收入:{}", operatingIncomeSum, operatingExpensesSum, money);
            vo.setOrderMoney(NumberUtil.mul(money, 100));
            vo.setOrderCount(Integer.valueOf(operationMap.getOrDefault("cycling_income_cnt", 0).toString()));
        }

        Map<Integer, Integer> workOrderMap = moveLogDao.selectTodayCount(dto).stream().collect(Collectors.toMap(WorkOrderVO::getType, WorkOrderVO::getWorkOrderCount));
        vo.setPowerOrderCount(workOrderMap.getOrDefault(1, 0));
        vo.setMoverOrderCount(workOrderMap.getOrDefault(2, 0));
        vo.setDispatchOrderCount(workOrderMap.getOrDefault(3, 0));
        //故障车辆数
        ItemsDTO itemsDTO = new ItemsDTO();
        BeanUtils.copyProperties(dto, itemsDTO);
        itemsDTO.setRegionId(dto.getRegionIds());
        Map<String, Object> map = workbenchApi.machineData(itemsDTO);
        vo.setPowerShortageCount(Integer.valueOf(map.getOrDefault("numberOfLowVoltageVehicles", "0").toString()));
        vo.setOutAreaCount(Integer.valueOf(map.getOrDefault("numberOfVehiclesOutArea", "0").toString()));
        vo.setFaultCount(Integer.valueOf(map.getOrDefault("numberOfFaultyVehicles", "0").toString()));
        return vo;
    }


}
